<script setup>
import {
    SearchOutlined,
    RedoOutlined,
    UploadOutlined,
    DownloadOutlined,
    EditOutlined,
    EyeOutlined,
    DeleteOutlined
} from '@ant-design/icons-vue';
import { h, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import ImportExcel from '@/components/importExcel/importExcel.vue';
import { importPatient, getPatientList, deletePatient } from '@/api/patientApi.js';
import HDK from '@/lib/HDK';
import { message, Modal } from 'ant-design-vue';

const loading = ref(false);
const tableData = ref([]);
const router = useRouter();
const ImportExcelRef = ref(null);
const importLoading = ref(false);
const columns = [
    { title: '登记号', dataIndex: 'admissionNumber', fixed: 'left', align: 'center' },
    { title: '病案号', dataIndex: 'caseNumber', fixed: 'left', align: 'center' },
    { title: '民族', dataIndex: 'ethnicity', width: 120, align: 'center', customRender: ({text}) => {
        return text === '1' ? '汉族' : '其他'
    } },
    { title: '婚姻状况', dataIndex: 'maritalStatus', width: 120, align: 'center' },
    { title: '性别', dataIndex: 'gender', width: 80, align: 'center' },
    { title: '年龄', dataIndex: 'age', width: 80, align: 'center', customRender: ({text}) => {
        return text ? `${text} 岁` : '/'
    }},
    { title: '体格检查-身高', dataIndex: 'height', align: 'center', customRender: ({text}) => {
        return text ? `${text} CM` : '/'
    }},
    { title: '体格检查-体重', dataIndex: 'weight', align: 'center', customRender: ({text}) => {
        return text ? `${text} KG` : '/'
    }},
    { title: '既往史-过敏史', dataIndex: 'allergyHistory', width: 200, align: 'center' },
    { title: '个人史-嗜烟', dataIndex: 'smokingHistory', width: 150, align: 'center' },
    { title: '嗜烟平均数', dataIndex: 'averageCigarettesPerDay', width: 150, align: 'center',customRender: ({text}) => {
        return text ? `${text} 支/日` : '/'
    }},
    { title: '嗜烟时间', dataIndex: 'smokingYears', width: 150, align: 'center', customRender: ({text}) => {
        return text ? `${text} 年` : '/'
    }},
    { title: '戒烟', dataIndex: 'quitSmoking', width: 100, align: 'center', customRender: ({text}) => {
        return text ? `${text}` : '/'
    } },
    { title: '戒烟时间', dataIndex: 'quitSmokingYears', width: 130, align: 'center', customRender: ({text}) => {
        return text ? `${text} 年` : '/'
    }},
    { title: '嗜酒', dataIndex: 'drinkingHistory', width: 100, align: 'center' },
    { title: '嗜酒平均数', dataIndex: 'averageAlcoholPerDay', align: 'center', customRender: ({text}) => {
        return text ? `${text} g/日` : '/'
    }},
    { title: '嗜酒时间', dataIndex: 'drinkingYears', width: 100, align: 'center', customRender: ({text}) => {
        return text ? `${text} 年` : '/'
    }},
    { title: '个人史-戒酒', dataIndex: 'quitDrinking', width: 130, align: 'center', customRender: ({text}) => {
        return text ? `${text}` : '/'
    }},
    { title: '个人史-戒酒时间', dataIndex: 'quitDrinkingYears', align: 'center', customRender: ({text}) => {
        return text ? `${text} 年` : '/'
    }},
    { title: '入院日期', dataIndex: 'admissionDate', align: 'center' },
    { title: '出院日期', dataIndex: 'dischargeDate', align: 'center' },
    { title: '入院科室', dataIndex: 'admissionDepartment', align: 'center' },
    { title: '当前科室名称', dataIndex: 'currentDepartment', width: 150, align: 'center' },
    { title: '操作', key: 'actions', align: 'center', fixed: 'right' }
];
const selectedRowKeys = ref([]);
const pagination = ref(HDK.page);
const queryForm = ref({
    page: 1,
    limit: 10,
    admissionNumber: '',
    caseNumber: ''
});

function onSelectChange(keys) {
    selectedRowKeys.value = keys;
}

function fetchData() {
    loading.value = true;
    queryForm.value.page = pagination.value.current;
    queryForm.value.limit = pagination.value.pageSize;
    getPatientList(queryForm.value)
        .then(res => {
            tableData.value = res.data;
            pagination.value.total = res.count;
        })
        .finally(() => {
            loading.value = false;
        })
}

function onEdit(record) {
    router.push(`/save-patient?id=${record.id}`);
}

function onDetail(record) {
    router.push(`/patient-detail?id=${record.id}`);
}

function onImport() {
    ImportExcelRef.value.showComponent();
}

function onImportData(file) {
    importLoading.value = true;
    const formData = new FormData();
    formData.append('file', file);
    importPatient(formData)
        .then(res => {
            HDK.info('导入成功');
            fetchData();
        })
        .finally(() => {
            importLoading.value = false;
        });
}

function onTableQuery() {
    pagination.value.current = 1;
    pagination.value.pageSize = 10;
    fetchData();
}

function onResetQuery() {
    pagination.value.current = 1;
    pagination.value.pageSize = 10;
    queryForm.value.admissionNumber = '';
    queryForm.value.caseNumber = '';
    fetchData();
}

function onDeleteItem(record) {
    Modal.confirm({
        title: '删除患者',
        centered: true,
        maskClosable: false,
        content: h('span', null, [
            h('span', null, '确定删除患者 '),
            h('strong', { style: 'color: red' }, record.userName),
            h('span', null, ' 吗？')
        ]),
        onOk() {
            deletePatient({ids: [record.id]})
            .then(res => {
                fetchData();
                HDK.info('删除成功');
            });
        }
    });
}

function onBatchDelete() {
    if (selectedRowKeys.value.length === 0) {
        message.warning('请选择要删除的患者');
        return;
    }

    Modal.confirm({
        title: '批量删除患者',
        centered: true,
        maskClosable: false,
        content: h('span', null, [
            h('span', null, `确定删除选中的 ${selectedRowKeys.value.length} 名患者数据吗？`)
        ]),
        onOk() {
            deletePatient({ids: selectedRowKeys.value})
            .then(res => {
                fetchData();
                HDK.info('删除成功');
            });
        }
    });
}

onMounted(() => {
    fetchData();
});

</script>

<template>
    <div>
        <a-card title="检索" size="small">
            <a-form layout="inline">
                <a-form-item label="登记号">
                    <a-input v-model:value="queryForm.admissionNumber" placeholder="请输入登记号" :disabled="loading" @keydown.enter="onTableQuery" />
                </a-form-item>
                <a-form-item label="病案号">
                    <a-input v-model:value="queryForm.caseNumber" placeholder="请输入病案号" :disabled="loading" @keydown.enter="onTableQuery" />
                </a-form-item>
                <a-form-item>
                    <a-space>
                        <a-button type="primary" :loading="loading" @click="onTableQuery">
                            <template #icon>
                                <SearchOutlined />
                            </template>
                            检索
                        </a-button>
                        <a-button :loading="loading" @click="onResetQuery">
                            <template #icon>
                                <RedoOutlined />
                            </template>
                            重置
                        </a-button>
                    </a-space>
                </a-form-item>
            </a-form>
        </a-card>
        <a-card title="列表" size="small" style="margin-top: 14px">
            <a-table 
                rowKey="id" 
                size="small" 
                :bordered="false" 
                :loading="loading" 
                :columns="columns"
                :data-source="tableData"
                :pagination="pagination"
                :scroll="{ x: 'max-content' }"
                :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)">

                <template #title>
                    <a-space>
                        <a-button type="primary" @click="onImport">
                            <template #icon>
                                <UploadOutlined />
                            </template>
                            导入患者数据
                        </a-button>
                        <a-button>
                            <template #icon>
                                <DownloadOutlined />
                            </template>
                            导出患者数据
                        </a-button>
                        <a-button type="primary" danger ghost :disabled="selectedRowKeys.length === 0" @click="onBatchDelete">
                            <template #icon>
                                <DeleteOutlined />
                            </template>
                            批量删除{{ selectedRowKeys.length ? `（已选择 ${selectedRowKeys.length} 条数据）` : ''}}
                        </a-button>
                    </a-space>
                </template>
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'actions'">
                        <a-space>
                            <a-button size="small" @click="onDetail(record)">
                                <template #icon>
                                    <EyeOutlined />
                                </template>
                                查看
                            </a-button>
                            <a-button size="small" type="primary" ghost @click="onEdit(record)">
                                <template #icon>
                                    <EditOutlined />
                                </template>
                                编辑
                            </a-button>
                            <a-button size="small" type="primary" danger ghost @click="onDeleteItem(record)">
                                <template #icon>
                                    <DeleteOutlined />
                                </template>
                                删除
                            </a-button>
                        </a-space>
                    </template>
                </template>
            </a-table>
        </a-card>

        <ImportExcel ref="ImportExcelRef" title="导入患者数据" :loading="importLoading" @upload="onImportData" />
    </div>
</template>

<style lang="less" scoped>
.page-name {
    font-size: 20px;
    color: #333;
    font-weight: bold;
}

:deep(.table-striped) {
    background-color: @second-bg-color;
}

:deep(.ant-table-title) {
    padding: 0 0 8px !important;
}
</style>